package com.hk.controller;

import com.hk.common.ret.RetCode;
import com.hk.common.ret.RetResponse;
import com.hk.common.util.StringUtils;
import com.hk.core.json.JSON;
import com.hk.core.json.JSONS;
import com.hk.dto.RegisterUser;
import com.hk.model.RentInfo;
import com.hk.model.ServerInfo;
import com.hk.model.User;
import com.hk.service.ServerInfoServiceImpl;
import com.hk.service.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@Slf4j
@Api(tags = {"index页面的数据接口"}, description = "IndexController")
public class IndexController {

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private ServerInfoServiceImpl serverInfoService;

    @GetMapping("/allServerInfo")
    @ApiOperation(value = "服务器信息列表", notes = "服务器信息列表")
    @JSONS({
            @JSON(exclude = "id", type = RentInfo.class),
            @JSON(exclude = "id", type = User.class)
    })
    public List<ServerInfo> allServerInfo() {

        List<ServerInfo> infos = serverInfoService.findAllServerInfo();
        log.error(infos.toString());
        return infos;
    }

    @PostMapping("/login")
    @ResponseBody
    @ApiOperation(value = "登录接口", consumes = "form/data", notes = "登录接口")
    public Object login(@RequestParam String loginName,
                        @RequestParam String password, @ApiIgnore HttpSession session) {
        User user = null;
        if (StringUtils.isNotBlank(loginName) && StringUtils.isNotBlank(password)) {
            user = userService.findOneUser(loginName, password);
            session.setAttribute("loginName", user);
        }
        RetCode retCode = user == null ? RetCode.NOT_FOUND_USERNOT_FOUND_USER : RetCode.SUCCESS;
        return RetResponse.makeRsp(retCode, user);
    }

    @PostMapping("/register")
    @ResponseBody
    @ApiOperation(value = "注册接口", consumes = "application/json", notes = "注册接口")
    public Object register(@RequestBody @Validated RegisterUser registerUser) {
        User user = registerUser.cloneDataToUser();
        User tempUser = userService.findOneUser(user.getLoginName(), user.getPassword());
        if (tempUser != null) {
            return RetResponse.makeRsp(RetCode.USER_EXISTED_USER);
        }
        user = userService.saveOneUser(user);
        RetCode retCode = user == null ? RetCode.FAIL : RetCode.SUCCESS;
        return RetResponse.makeRsp(retCode, user);
    }
}
